<template>
  <div class="je-admin-header-infomation">
    <div class="infomation">
      <div
        class="infomation-left"
        @mouseenter="uploadPhoto = false"
        @mouseleave="uploadPhoto = true"
        @click="changePhoto"
      >
        <div v-if="uploadPhoto">
          <span v-if="!photoUrl" class="usename-img">{{ username }}</span>
          <img v-else :src="photoUrl" class="user-img-url" />
        </div>
        <div v-if="!uploadPhoto" class="upload-img">上传</div>
      </div>
      <div class="infomation-right">
        <div class="name">{{ currentUser.name || '暂无' }}</div>
        <div class="dept">{{ currentUser.organization.name }}</div>
      </div>
      <SecurityUser />
    </div>
    <div class="infomation-setting">
      <div class="text" @click="changeDept()">切换部门</div>
      <div class="line"></div>
      <div class="text" @click="showModal('Infomation')">个人中心</div>
      <div class="line"></div>
      <div class="text" @click="showModal('ChangePassword')">修改密码</div>
    </div>
  </div>
  <Infomation
    v-if="activeModal == 'Infomation'"
    :visible="activeModal == 'Infomation'"
    :current-user="currentUser"
    :url-img="photoUrl"
    @closeModal="activeModal = ''"
  />
  <ChangePassword
    v-if="activeModal == 'ChangePassword'"
    :visible="activeModal == 'ChangePassword'"
    @closeModal="activeModal = ''"
  />
</template>
<script>
  import { defineComponent, toRefs, reactive } from 'vue';
  import Infomation from './infomation.vue';
  import ChangePassword from './change-password.vue';
  import {
    getCurrentUser,
    uploadFile,
    getFileUrlByKey,
    decode,
    encode,
    initCurrentAccount,
    getCurrentAccount,
  } from '@jecloud/utils';
  import { showTreeSelect } from '@jecloud/func';
  import { changeUserPhoto, getChangeDeptList, editSwitchDept } from './api/index';
  import { Modal, Data } from '@jecloud/ui';
  import SecurityUser from '../security/security-user';
  export default defineComponent({
    name: 'AdminHeaderInfomation',
    components: { Infomation, ChangePassword, SecurityUser },
    emits: ['changeHeaderUrl', 'changeProver'],
    setup(props, { emit }) {
      const state = reactive({
        activeModal: '',
        currentUser: getCurrentUser(),
        uploadPhoto: true,
        fileKey: '',
        photoUrl: '',
        username: '',
        filename: '',
      });

      const { name, avatar } = getCurrentUser();
      const url = (avatar && getFileUrlByKey(decode(avatar)[0]?.fileKey)) || '';
      state.photoUrl = url || '';
      state.username = name && name.slice(-2);
      const methods = {
        // 切换部门
        changeDept() {
          emit('changeProver');
          // 获取列表部门的数据
          getChangeDeptList({ accountId: getCurrentAccount().id })
            .then((res) => {
              if (res.length <= 1) {
                Modal.message('暂无其他部门可切换！', 'info');
                return false;
              }
              const treeStore = Data.Store.useTreeStore({
                data: res.children,
              });
              showTreeSelect({
                title: '切换部门',
                store: treeStore,
                autoLoad: false,
                hideRefresh: true,
                configInfo: ',,,S',
                callback: ({ rows }) => {
                  if (rows.length <= 0) {
                    Modal.message('请先选择要切换的部门！', 'info');
                    return false;
                  }
                  editSwitchDept({ accountId: getCurrentAccount().id, deptId: rows[0].id })
                    .then(() => {
                      Modal.message('切换部门成功', 'success');
                      const url = window.location.origin;
                      window.location.href = url;
                    })
                    .catch((error) => {
                      Modal.alert(error.message, 'error');
                    });
                },
              });
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
            });
        },
        showModal(type) {
          state.activeModal = type;
        },
        // 修改头像
        changePhoto() {
          uploadFile({
            onFileAdded({ file }) {
              // 添加文件
              state.filename = file.name;
            },
            onUploadStart() {
              Modal.message(`图片：${state.filename}，正在上传中！`, 'success');
            },
          }).then((files) => {
            state.uploadPhoto = true;
            // 这就是头像的fileKey
            const fileKey = files && files[0] && files[0].fileKey;
            state.fileKey = fileKey || '';
            fileKey &&
              changeUserPhoto({ accountId: getCurrentAccount().id, avatar: encode(files) })
                .then((res) => {
                  state.photoUrl = getFileUrlByKey(fileKey);
                  emit('changeHeaderUrl', encode(files));
                  initCurrentAccount();
                  Modal.message(res.message, 'success');
                })
                .catch((error) => {
                  Modal.alert(error.message, 'error');
                });
          });
        },
      };
      return { ...methods, ...toRefs(state) };
    },
  });
</script>
<style lang="less">
  .je-admin-header-infomation {
    .infomation {
      display: flex;
      align-items: center;
      padding-bottom: 12px;
      border-bottom: 1px solid #f5f5f5;
      .infomation-left {
        width: 38px;
        height: 38px;
        flex: none;
        text-align: center;
        border-radius: 100%;
        cursor: pointer;
        background: #d3d3d3;
        // i {
        //   font-size: 20px;
        // }
        .usename-img {
          display: inline-block;
          width: 38px;
          height: 38px;
          color: #fff;
          border-radius: 100%;
          font-size: 14px;
          line-height: 38px;
          background: #faa03a;
          text-align: center;
        }
        .user-img-url {
          width: 38px;
          height: 38px;
          border-radius: 100%;
        }
        .upload-img {
          font-size: 12px;
          line-height: 38px;
          opacity: 0.65;
          color: #fff;
          background: #3e3d3d;
          border-radius: 100%;
          cursor: pointer;
        }
      }
      .infomation-right {
        margin: 0 20px 0 10px;
        flex: 1;

        .name {
          color: #3f3f3f;
          color: 14px;
        }
        .dept {
          font-size: 12px;
          color: #3f3f3f;
          line-height: 20px;
        }
      }
    }
    .infomation-setting {
      display: flex;
      padding-top: 20px;
      justify-content: center;
      .line {
        margin: 0 20px;
        width: 1px;
        height: 20px;
        background: #f5f5f5;
      }
      .text {
        font-size: 14px;
        color: #333333;
        cursor: pointer;
        &:hover {
          color: @primary-color;
        }
      }
    }
  }
</style>
